package com.property.demo.controller;

import com.property.demo.model.*;
import com.property.demo.repository.*;
import com.property.demo.dto.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.domain.Sort;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/dashboard")
public class DashboardController {
    
    private static final Logger logger = LoggerFactory.getLogger(DashboardController.class);

    @Autowired
    private CommunityRepository communityRepository;

    @Autowired
    private BuildingRepository buildingRepository;

    @Autowired
    private HomeRepository homeRepository;

    @Autowired
    private OwnerRepository ownerRepository;

    @Autowired
    private ParkingRepository parkingRepository;

    @Autowired
    private ParkingUsageRepository parkingUsageRepository;

    @Autowired
    private RepairRepository repairRepository;

    @Autowired
    private ComplaintRepository complaintRepository;

    @Autowired
    private MailboxRepository mailboxRepository;
    
    public DashboardController() {
        logger.info("DashboardController 初始化");
    }

    /**
     * 获取统计卡片数据
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getStats() {
        logger.info("调用 getStats() API");
        Map<String, Object> stats = new HashMap<>();
        
        // 获取小区总数
        long communityCount = communityRepository.count();
        
        // 获取房产总数
        long homeCount = homeRepository.count();
        
        // 获取停车位总数
        long parkingCount = parkingRepository.count();
        
        // 获取业主总数
        long ownerCount = ownerRepository.count();
        
        stats.put("communityCount", communityCount);
        stats.put("homeCount", homeCount);
        stats.put("parkingCount", parkingCount);
        stats.put("ownerCount", ownerCount);
        
        logger.info("getStats() API 返回数据: {}", stats);
        return ResponseEntity.ok(stats);
    }
    
    /**
     * 获取小区房产分布数据
     */
    @GetMapping("/community-homes")
    public ResponseEntity<List<Map<String, Object>>> getCommunityHomes() {
        logger.info("调用 getCommunityHomes() API");
        List<Community> communities = communityRepository.findAll();
        List<Map<String, Object>> result = new ArrayList<>();
        
        for (Community community : communities) {
            Map<String, Object> item = new HashMap<>();
            long homeCount = homeRepository.countByCommunityId(community.getId());
            
            item.put("name", community.getName());
            item.put("value", homeCount);
            
            result.add(item);
        }
        
        logger.info("getCommunityHomes() API 返回 {} 条数据", result.size());
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取房产使用情况数据
     */
    @GetMapping("/home-usage")
    public ResponseEntity<Map<String, Object>> getHomeUsage() {
        logger.info("调用 getHomeUsage() API");
        List<Community> communities = communityRepository.findAll();
        List<String> communityNames = communities.stream()
                .map(Community::getName)
                .collect(Collectors.toList());
        
        List<Map<String, Object>> soldData = new ArrayList<>();
        List<Map<String, Object>> rentedData = new ArrayList<>();
        List<Map<String, Object>> vacantData = new ArrayList<>();
        
        for (Community community : communities) {
            long soldCount = homeRepository.countByCommunityIdAndStatus(community.getId(), "已售出");
            long rentedCount = homeRepository.countByCommunityIdAndStatus(community.getId(), "已出租");
            long vacantCount = homeRepository.countByCommunityIdAndStatus(community.getId(), "空置");
            
            Map<String, Object> soldItem = new HashMap<>();
            soldItem.put("name", community.getName());
            soldItem.put("value", soldCount);
            soldData.add(soldItem);
            
            Map<String, Object> rentedItem = new HashMap<>();
            rentedItem.put("name", community.getName());
            rentedItem.put("value", rentedCount);
            rentedData.add(rentedItem);
            
            Map<String, Object> vacantItem = new HashMap<>();
            vacantItem.put("name", community.getName());
            vacantItem.put("value", vacantCount);
            vacantData.add(vacantItem);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("communities", communityNames);
        result.put("sold", soldData);
        result.put("rented", rentedData);
        result.put("vacant", vacantData);
        
        logger.info("getHomeUsage() API 返回数据，包含 {} 个社区", communities.size());
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取停车位使用情况数据
     */
    @GetMapping("/parking-usage")
    public ResponseEntity<List<Map<String, Object>>> getParkingUsage() {
        logger.info("调用 getParkingUsage() API");
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 获取已售停车位数量
        long soldCount = parkingUsageRepository.countByUsageType("购买");
        Map<String, Object> soldItem = new HashMap<>();
        soldItem.put("name", "已售");
        soldItem.put("value", soldCount);
        result.add(soldItem);
        
        // 获取已租停车位数量
        long rentedCount = parkingUsageRepository.countByUsageType("租赁");
        Map<String, Object> rentedItem = new HashMap<>();
        rentedItem.put("name", "已租");
        rentedItem.put("value", rentedCount);
        result.add(rentedItem);
        
        // 获取临时使用停车位数量
        long tempCount = parkingUsageRepository.countByUsageType("临时");
        Map<String, Object> tempItem = new HashMap<>();
        tempItem.put("name", "临时使用");
        tempItem.put("value", tempCount);
        result.add(tempItem);
        
        // 计算空置停车位数量
        long totalCount = parkingRepository.count();
        long usedCount = soldCount + rentedCount + tempCount;
        long vacantCount = totalCount - usedCount;
        Map<String, Object> vacantItem = new HashMap<>();
        vacantItem.put("name", "空置");
        vacantItem.put("value", vacantCount > 0 ? vacantCount : 0);
        result.add(vacantItem);
        
        logger.info("getParkingUsage() API 返回 {} 条数据", result.size());
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取服务请求趋势数据（近7天）
     */
    @GetMapping("/service-trend")
    public ResponseEntity<Map<String, Object>> getServiceTrend() {
        logger.info("调用 getServiceTrend() API");
        // 获取最近7天的日期
        List<String> days = new ArrayList<>();
        List<Long> repairCounts = new ArrayList<>();
        List<Long> complaintCounts = new ArrayList<>();
        List<Long> mailboxCounts = new ArrayList<>();
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d");
        
        for (int i = 6; i >= 0; i--) {
            LocalDate date = LocalDate.now().minusDays(i);
            LocalDateTime startOfDay = date.atStartOfDay();
            LocalDateTime endOfDay = date.plusDays(1).atStartOfDay().minusSeconds(1);
            
            String formattedDate = date.format(formatter);
            days.add(formattedDate);
            
            // 统计维修请求
            long repairCount = repairRepository.countByReportTimeBetween(startOfDay, endOfDay);
            repairCounts.add(repairCount);
            
            // 统计投诉
            long complaintCount = complaintRepository.countBySubmitTimeBetween(startOfDay, endOfDay);
            complaintCounts.add(complaintCount);
            
            // 统计信箱留言
            long mailboxCount = mailboxRepository.countBySubmitTimeBetween(startOfDay, endOfDay);
            mailboxCounts.add(mailboxCount);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("days", days);
        result.put("repairs", repairCounts);
        result.put("complaints", complaintCounts);
        result.put("mailboxes", mailboxCounts);
        
        logger.info("getServiceTrend() API 返回数据，包含 {} 天的趋势", days.size());
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取人员分布统计数据
     */
    @GetMapping("/personnel-distribution")
    public ResponseEntity<Map<String, Object>> getPersonnelDistribution() {
        logger.info("调用 getPersonnelDistribution() API");
        List<Community> communities = communityRepository.findAll();
        List<String> communityNames = communities.stream()
                .map(Community::getName)
                .collect(Collectors.toList());
        
        List<Long> ownerCounts = new ArrayList<>();
        List<Long> familyCounts = new ArrayList<>();
        List<Long> visitorCounts = new ArrayList<>();
        
        for (Community community : communities) {
            // 统计业主数量
            long ownerCount = ownerRepository.countByCommunityId(community.getId());
            ownerCounts.add(ownerCount);
            
            // 假设家庭成员是业主的2倍（实际项目中应该有专门的表）
            long familyCount = ownerCount * 2;
            familyCounts.add(familyCount);
            
            // 假设访客是业主的0.5倍（实际项目中应该有专门的表）
            long visitorCount = Math.round(ownerCount * 0.5);
            visitorCounts.add(visitorCount);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("communities", communityNames);
        result.put("owners", ownerCounts);
        result.put("families", familyCounts);
        result.put("visitors", visitorCounts);
        
        logger.info("getPersonnelDistribution() API 返回数据，包含 {} 个社区", communities.size());
        return ResponseEntity.ok(result);
    }
} 